Grokking Google Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Google Easy
Add Binary (easy)
Solution: Add Binary
Valid Mountain Array (easy)
Solution: Valid Mountain Array
Set Mismatch (easy)
Solution: Set Mismatch
Is Subsequence (easy)
Solution: Is Subsequence
Length of Last Word (easy)
Solution: Length of Last Word
Search Insert Position (easy)
Solution: Search Insert Position
Repeated Substring Pattern (easy)
Solution: Repeated Substring Pattern
Monotonic Array (easy)
Solution: Monotonic Array
Count Nodes Equal to Average of Subtree (easy)
Solution: Count Nodes Equal to Average of Subtree
Find the Difference (easy)
Solution: Find the Difference
How Many Numbers Are Smaller Than the Current Number (easy)
Solution: How Many Numbers Are Smaller Than the Current Number
Binary Tree Paths (easy)
Solution: Binary Tree Paths
Find the Difference of Two Arrays (easy)
Solution: Find the Difference of Two Arrays
Merge Strings Alternately (easy)
Solution: Merge Strings Alternately
Reverse a LinkedList (easy)
Solution: Reverse a LinkedList
Google Medium
Gray Code (medium)
Solution: Gray Code
2 Keys Keyboard (medium)
Solution: 2 Keys Keyboard
Arithmetic Slices (medium)
Solution: Arithmetic Slices
Unique Length-3 Palindromic Subsequences (medium)
Solution: Unique Length-3 Palindromic Subsequences
Minimum Difference Between Largest and Smallest Value in Three Moves (medium)
Solution: Minimum Difference Between Largest and Smallest Value in Three Moves
Letter Combinations of a Phone Number (medium)
Solution: Letter Combinations of a Phone Number
01 Matrix (medium)
Solution: 01 Matrix
Maximum Points You Can Obtain from Cards (medium)
Solution: Maximum Points You Can Obtain from Cards
Strobogrammatic Number II (medium)
Solution: Strobogrammatic Number II
Maximum Length of Semi-Decreasing Subarrays (medium)
Solution: Maximum Length of Semi-Decreasing Subarrays
Minimum Area Rectangle (medium)
Solution: Minimum Area Rectangle
Count Unreachable Pairs of Nodes in an Undirected Graph (medium)
Solution: Count Unreachable Pairs of Nodes in an Undirected Graph
Single Number II (medium)
Solution: Single Number II
4Sum II (medium)
Solution: 4Sum II
Furthest Building You Can Reach (medium)
Solution: Furthest Building You Can Reach
Minimizing Array After Replacing Pairs With Their Product (medium)
Solution: Minimizing Array After Replacing Pairs With Their Product
Fair Distribution of Cookies (medium)
Solution: Fair Distribution of Cookies
Find Leaves of Binary Tree (medium)
Solution: Find Leaves of Binary Tree
Rotate Image (medium)
Solution: Rotate Image
Combination Sum (medium)
Solution: Combination Sum
Implement Trie (Prefix Tree) (medium)
Solution: Implement Trie (Prefix Tree)
Number of Islands (medium)
Solution: Number of Islands
Edit Distance (medium)
Solution: Edit Distance
Container With Most Water (Medium)
Solution: Container With Most Water
Meeting Rooms II (medium)
Solution: Meeting Rooms II
Shortest Subarray with Sum at Least K (hard)
Solution: Shortest Subarray with Sum at Least K
Reverse Pairs (hard)
Solution: Reverse Pairs
Nth Magical Number (hard)
Solution: Nth Magical Number
Candy (hard)
Solution: Candy
Arithmetic Slices II - Subsequence (hard)
Solution: Arithmetic Slices II - Subsequence
Burst Balloons (hard)
Solution: Burst Balloons
Sum of Distances in Tree (hard)
Solution: Sum of Distances in Tree
Maximum Score of a Good Subarray (hard)
Solution: Maximum Score of a Good Subarray
Trapping Rain Water (hard)
Solution: Trapping Rain Water
First Missing Positive (hard)
Solution: First Missing Positive
Solution: Maximum Points You Can Obtain from Cards

Problem Statement

You are given several cards arranged in a single row, where ith card has cardPoints[i] points.

In a single step, you can take one card from the start or from the end of the row. You have to take exactly k cards.

The score is the sum of the points of the cards you have withdrawn.

Given the cardPoints array containing integers and the integer k, return the maximum score you can obtain.

Examples

  • Example 1:

    • Input: cardPoints = [10, 14, 7, 2, 8, 9, 4], k = 3
    • Expected Output: 31
    • Justification: The best strategy is to take the cards with 10, 14, and 7 points. The maximum score will be 10 + 14 + 7 = 31.
  • Example 2:

    • Input: cardPoints = [1, 2, 3, 4, 5, 6], k = 2
    • Expected Output: 11
    • Justification: Taking the two cards from the right end (5 and 6) gives us the highest score. The sum here is higher than any other combination of 2 cards.
  • Example 3:

    • Input: cardPoints = [91, 24, 36, 48, 72, 19, 29], k = 4
    • Expected Output: 211
    • Justification: The optimal move is to take 91 from the left, then 29, 19, and 72 from the right, achieving the maximum possible score.

Solution

To solve this problem, the intuitive approach might be to try all possible combinations of picking cards from both ends. However, this approach is not feasible due to its high computational complexity. Instead, a more efficient strategy involves focusing on the sub-array of cards that we will not select. If we can minimize the total points of the cards not chosen, we effectively maximize the points from the cards we do select. This approach is both time-efficient and logically sound because it flips the problem on its head by concentrating on what we leave behind rather than what we take.

The essence of this strategy is to use a sliding window technique to identify the sub-array of length n-k (where n is the total number of cards and k is the number of cards to select) that has the minimum sum. This sub-array represents the cards we will not take. By subtracting this sum from the total points available, we obtain the maximum points we can score. This method is efficient and sidesteps the need for exhaustive search, making it a practical solution for the problem at hand.

Step-by-step Algorithm

  1. Initialize Variables:

    • Calculate the totalSum of all card points in the array.
    • Determine the number of cards n.
    • Calculate the size of the window as windowSize = n - k. This window represents the cards that are not selected.
    • Set currentSum to the sum of the first windowSize elements in the array.
    • Initialize minSubArraySum with the value of currentSum.
  2. Find the Minimum Sum Sub-array:

    • Starting from index windowSize, iterate through the cardPoints array.
    • For each position, adjust currentSum by subtracting the element at the start of the window and adding the current element (this effectively slides the window one position to the right).
    • Update minSubArraySum if the new currentSum is less than the current minSubArraySum.
  3. Calculate Maximum Score:

    • The maximum score is calculated as maxScore = totalSum - minSubArraySum. This is because the minimum sum of the non-selected cards subtracted from the total sum gives the maximum possible sum of the selected cards.
  4. Return maxScore as the result.

Algorithm Walkthrough

Given the input [91, 24, 36, 48, 72, 19, 29], k = 4.

  1. Initialize Variables:

    • totalSum = 91 + 24 + 36 + 48 + 72 + 19 + 29 = 319
    • n = 7
    • windowSize = n - k = 7 - 4 = 3
    • currentSum = 91 + 24 + 36 = 151
    • minSubArraySum = 151
  2. First Window: (already calculated)

    • window = [91, 24, 36]
    • currentSum = 151
    • minSubArraySum = 151
  3. Slide the Window:

    • Slide 1:
      • Remove 91 (start of the window), add 48 (new end of the window).
      • currentSum = 151 - 91 + 48 = 108
      • minSubArraySum = 108 (updated because 108 < 151)
    • Slide 2:
      • Remove 24, add 72.
      • currentSum = 108 - 24 + 72 = 156
      • minSubArraySum remains 108 (since 156 > 108)
    • Slide 3:
      • Remove 36, add 19.
      • currentSum = 156 - 36 + 19 = 139
      • minSubArraySum remains 108 (since 139 > 108)
    • Slide 4:
      • Remove 48, add 29.
      • currentSum = 139 - 48 + 29 = 120
      • minSubArraySum remains 108 (since 120 > 108)
  4. Calculate Maximum Score:

    • maxScore = totalSum - minSubArraySum = 319 - 108 = 211
  5. Result:

    • The maximum score that can be obtained is 211.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

The time complexity of the algorithm is , where n is the length of the cardPoints array. This efficiency is achieved because the algorithm iterates over the array only once to calculate the total sum and then performs a single pass with a sliding window to find the minimum sum of the sub-array of size n-k. The operations within each iteration are constant time operations, leading to a linear time complexity.

Space Complexity

The space complexity of the algorithm is . This is because the algorithm uses a fixed amount of extra space regardless of the input size.

Maximum Points You Can Obtain from Cards (medium)
Strobogrammatic Number II (medium)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity